import { Sequelize } from 'sequelize-typescript';
import * as fs from 'fs';
import * as path from 'path';
import config from '../config';

export const sequelize = new Sequelize({
  database: config.db.name,
  dialect: config.db.dialect,
  username: config.db.user,
  password: config.db.password,
  timezone: config.db.timezone,
  // 修改sql输出
  logging: false
});

let isLoaded = false;

// 只加载一次
export const loadModels = () => {
  if (isLoaded) return;
  // 自动加载模型
  const fileNames = fs.readdirSync(path.resolve(__dirname, './'))
    .filter(fileName => fileName !== path.basename(__filename) && fileName !== 'Base.ts');
  fileNames.forEach((fileName) => {
    const model = require(`./${fileName}`).default;
    sequelize.addModels([model]);
    const modelName = fileName.slice(0, fileName.length - 3);
  });
  isLoaded = true;
};
